package com.manage.controller;

import com.manage.pojo.Admin;
import com.manage.service.AdminService;
import com.manage.utils.FBJSONResult;
import com.manage.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Api(value = "有关管理员的操作", tags = {"有关管理员的操作"})
public class AdminController {

    @Autowired
    private AdminService adminService;

    @ApiOperation(value = "管理员用户注册", notes = "管理员用户注册接口")
    @PostMapping("/admin/adminRegist")
    public FBJSONResult adminRegist(@RequestBody Admin admin) throws Exception {
        admin.setAdminId(admin.getAdminId());
        admin.setAdminUsername(admin.getAdminUsername());
        admin.setAdminPassword(MD5Utils.getMD5Str(admin.getAdminPassword()));
        admin.setAdminName(admin.getAdminName());
        admin.setAdminPhone(admin.getAdminPhone());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        admin.setCreateTime(sdf.format(new Date()));
        adminService.saveAdmin(admin);
        return FBJSONResult.ok();
    }

    @ApiOperation(value = "管理员用户登录", notes = "管理员用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adminId", value = "管理员用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "adminPassword", value = "管理员用户密码", required = true, dataType = "String", paramType = "query")})
    @PostMapping("/admin/adminLogin")
    public FBJSONResult adminLogin(String adminId, String adminPassword) throws Exception {
        Admin adminResult = adminService.queryAdminForLogin(adminId, MD5Utils.getMD5Str(adminPassword));
        if(adminResult != null) {
            adminResult.setAdminPassword("");
            return FBJSONResult.ok(adminResult);
        } else {
            return FBJSONResult.errorMsg("用户名或密码不对，请重新输入！");
        }
    }

    @ApiOperation(value = "管理员用户删除", notes = "管理员用户删除接口")
    @ApiImplicitParam(name = "adminId", value = "管理员用户id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/admin/adminDelete")
    public FBJSONResult adminDelete(String adminId) throws Exception {
        if(StringUtils.isBlank(adminId)) {
            return FBJSONResult.errorMsg("用户id不能为空!");
        } else {
            adminService.deleteAdmin(adminId);
            return FBJSONResult.ok("删除成功!");
        }
    }

}
